package com.my.springbootvalidation.controller;

import com.my.common.result.R;
import com.my.springbootvalidation.bean.ValidationBean;
import com.my.springbootvalidation.group.IdCheck;
import com.my.springbootvalidation.group.InsertCheck;
import com.my.springbootvalidation.group.UpdateCheck;
import com.my.springbootvalidation.repository.ValidationRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

/**
 * @Author marshal
 * @Date 2021-08-03 9:52 PM
 */
@RestController
@RequestMapping("/validation")
public class ValidationController {


    @Autowired
    private ValidationRepository repository;

    /**
     *  只是校验 InsertCheck.class 这个 group 的字段
     *
     * @param bean
     * @return
     */
    @PostMapping("/add")
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Object> add(@RequestBody @Validated(InsertCheck.class) ValidationBean bean) {
        return R.success(repository.save(bean));
    }

    /**
     *  更新的时候使用 UpdateCheck.class 这个 group
     *
     * @param bean
     * @return
     */
    @PostMapping("/update")
    @ExceptionHandler
    public R<Object> update(@RequestBody  @Validated(UpdateCheck.class) ValidationBean bean) {
        ValidationBean oldBean = repository.getById(bean.getId());
        ValidationBean newBean = new ValidationBean();
        BeanUtils.copyProperties(oldBean, newBean);
        return R.success(repository.save(newBean));
    }

    /**
     *  删除的时候只需要使用 IdCheck.class 这个 group 就好了
     *
     * @param bean
     * @return
     */
    @PutMapping("/delete")
    public R<Object> delete(@RequestBody @Validated(IdCheck.class) ValidationBean bean) {
        repository.delete(bean);
        return R.success();
    }
}
